<template>
<div class="layout-app" ref='myBox'>
	<!-- main -->
<el-dialog :title="diglogTile" :visible.sync="exaDialogVisible" width="58%" :before-close="handleClose" :destroy-on-close='true' :modal="false">
		<!-- 新增 -->
	<div class="addAcc">
			<!-- tabs -->
			<div class="tabs">
				<div class="tabsMain">
					<!-- 表单 -->
					<el-form ref="form" :model="addForm" label-width="99px" size="mini" :disabled="totaldisabled">
						<el-row :gutter="8">
							<el-col :xs="val.xs" :sm="val.xs" :md="val.md" :lg="val.lg" :xl="val.xl" type="flex" v-for="(val,i) in formType" :key="i">
								<!-- input -->
								<el-form-item v-if="val.type == 'input'" :label="val.label" :prop="val.modelValue">
									<el-input :suffix-icon='val.prefix' v-model="$data.addForm[val.modelValue]" :placeholder="val.placeholder" :disabled="val.disabled" ></el-input>
								</el-form-item>
								<!-- select -->
								<el-form-item v-if="val.type == 'select'" :label="val.label" :prop="val.modelValue">
									<el-select v-model="$data.addForm[val.modelValue]" filterable placeholder="请选择" @focus="headersname(val,i)"
									:disabled="val.disabled">
										<el-option v-for="item in $data[val.op]" :key="item.id" :label="item.label" :value="item.id">
											<div style="font-size: 12px;display: flex;justify-content: start;align-items: center;">
												<span>{{ item.id }}</span>
												<span style="margin-left: 12px;">{{ item.label }}</span>
											</div>
										</el-option>
									</el-select>
								</el-form-item>
								<!-- date -->
								<el-form-item v-if="val.type == 'date'" :label="val.label" :prop="val.modelValue">
									<el-date-picker class="autoWidth" :disabled="val.disabled" type="date" value-format="yyyy-MM-dd" v-model="$data.addForm[val.modelValue]"></el-date-picker>
								</el-form-item>
								<!-- btn -->
								<el-form-item v-if="val.type == 'btn'">
									<el-button type="primary" plain @click="clickEvents(val,i)">{{ val.label }}</el-button>
								</el-form-item>
							</el-col>
						</el-row>
					</el-form>
					<!-- table -->
					<div class="table">
						<el-table :data="tableData" border @row-dblclick="handledbRow">
							<el-table-column v-for="(col, inx) in tableRows" :key="inx" :type="col.type" :prop="col.prop" :label="col.name" :width="columnWidth(col, tableData)"></el-table-column>
							<!-- fixed -->
							<el-table-column fixed="left" label="行号" type="index" width="68" align="center"></el-table-column>
						</el-table>
						<div class="total">
							<span>合计金额：</span><el-input v-model="totalAmt" style="width: 128px;" size="mini" :disabled='totaldisabled'></el-input>
						</div>
					</div>
				</div>
			</div>
			<!-- 提交 -->
			<div v-if="diglogTile === '草稿'" slot="footer" class="dialog-footer">
				<el-button :loading="loading" size="mini" type="primary" @click="Submit">确定提交</el-button>
				<el-button size="mini" @click="exaDialogVisible = false">取消</el-button>
			</div>
			<!-- 审核 -->
			<div v-if="diglogTile === '审核'" slot="footer" class="dialog-footer">
				<el-button :loading="loading" size="mini" type="danger" @click="refuseExamine">拒绝审核</el-button>
				<el-button :loading="loading" size="mini" type="primary" @click="exaSubmit">确定审核</el-button>
				<el-button size="mini" @click="exaDialogVisible = false">取消</el-button>
			</div>
			<!-- 过单 -->
			<div v-if="diglogTile === '过单'" slot="footer" class="dialog-footer">
				<el-button :loading="loading" size="mini" type="danger" @click="refusePassOrder">拒绝过单</el-button>
				<el-button :loading="loading" size="mini" type="primary" @click="passOrderSubmit">确定过单</el-button>
				<el-button size="mini" @click="exaDialogVisible = false">取消</el-button>
			</div>
			<!-- 查看 -->
			<div v-if="diglogTile === '查看药品采购计划'" slot="footer" class="dialog-footer">
				<el-button size="mini" type="primary" @click="dy">打印</el-button>
				<el-button size="mini" @click="exaDialogVisible = false">关闭</el-button>
			</div>
	</div>
</el-dialog>
</div>
</template>

<script>
// self
import exaType from './AddPlanType.js'
import addForm from './addForm.js' //Form表单
// import nationality from './nationality.js'
// prop

// ext
// import { getLunar } from 'chinese-lunar-calendar'

// 接口
import { TcmDetail,toExamineTcm,selectInformation,selectDropDownList} from "@/api/systemCatalogue/traMedici.js";
export default {
	props: ['parentMethod'],
	components:{
		
	},
	data(){
		return{
			//str
			diglogTile:'', // 动态页面的动态标题
			tableWidth:'', //右侧表格动态宽度
			totalAmt:'', //合计金额
			value:'',
			deptCode:'',
			cbValue:'',
			lsValue:'',
			getLunarDay: '',
			areaCode:'',
			areaPName:'',
			idx:'',
			//num
			
			//ble
			disabled:true,
			totaldisabled:true,
			exaDialogVisible:false,
			//arr
			formType:[],
			tableData:[],
			selectOption:[{id:2,label:'中药库',value:'中药库'}],
			ghdwOption:[],
			nameOption:[],
			tableRows:[
				{ name:"药品名称", prop:"drugName", type:""},{ name:"规格描述", prop:"drugSpec", type:"" },
				{ name:"生产厂家", prop:"prodentpName", type:"" },
				{ name:"剂量单位", prop:"dosUnt", type:"" },{ name:"参考单价", prop:"purcPric", type:"" },
				{ name:"参考金额", prop:"purcPric", type:"" },{ name:"供货单位", prop:"supplyCandidateName", type:"" },
				// { name:"合同数量", prop:"gdTime", type:"" },{ name:"已购数量", prop:"zf", type:"" },{ name:"库存数量", prop:"ph", type:"" },
				// { name:"近期销量", prop:"scrq", type:"" }
			],
			//obj
			lists:{
				id:'',
				manufacturerName:'', //生产厂家名称
				clinicId:'', //诊所序号
				docId:'', //采购计划表id
				drugId:'', //药品id
				prodentpNameId:'', //生成厂家序号
				purCnt:'', //采购数量
				purcAmt:'', //参考金额
				purcPric:'', //参考单价
				remarks:'', //备注
				stockCnt:'', //库存数量
				supplyCandidateName:'', //供货单位名称
				unt:'', //剂量单位
			},
			addForm:{},
			options:[],
			ssrOption:[],
			gysOption:[],
		}
	},
	mounted() {
		this.getdatas();
		// 获取接口参数
		this.getAddForm();
		//获取动态盒子宽度，实时赋值给右侧
		this.$nextTick(() => {
		    const box = this.$refs.myBox;
		    this.tableWidth = box.offsetWidth - 288;
		    console.log('盒子的宽度是:', this.tableWidth);
		});
		
	},
	methods:{
		// 打开model 获取采购计划数据
		async openModel(parm){
			this.diglogTile = parm.name
			console.log(this.diglogTile);
			this.exaDialogVisible = true;
			let res = await TcmDetail({id:parm.id})
			console.log(res,'获取采购计划');
			if(res.code === 200){
				this.totalAmt = res.data.totalAmt
				this.addForm = res.data
				this.tableData = res.data.list
			}else{
				this.$message.error('系统错误！'+res.message)
			}
			
		},
		async getdatas(){
			// 员工档案信息 = > 申请人
			let res = await selectInformation()
			this.ssrOption = res.data.map(obj => {
			  // 将 name 替换为 label，并保留其他字段
			  return { label: obj.fullName , ...obj };
			});
			// 供应商下拉列表
			let rs = await selectDropDownList()
			this.gysOption = rs.data.content.map(obj => {
			  // 将 name 替换为 label，并保留其他字段
			  return { label: obj.supplierName , ...obj };
			});
		},
		// 时间处理
		deleteRow(index, rows) {
		  rows.splice(index, 1);
		},
		handleSelectCost(val) {
		  this.addForm.nativePlace = val.join(',')
		},
		// 挂载或销毁前后重新赋值后端参数
		getAddForm(){
			// 左侧提交表单
			this.addForm = addForm.map(v => {return v })[0]; // Form
			this.addMainForm = this.addForm.list[0]
			console.log(this.addForm,'原始的接口参数数据');
			// 定义数据来源
			this.formType = exaType.map(function(val) { return val })
			// this.formMainType = AccMainType.map(function(val) { return val })
			// 解构赋值排除 list 属性 => 弃用
			// this.addHeadrForm = addForm.map(item => { let { list, ...newItem } = item; return newItem })[0];
		},
		testDate(val,i){
			this.idx = val.id
		},
		handleClose(done) {
			done();
		},
		// 确定提交
		Submit(){
			this.addForm.state = 2
			console.log(this.addForm);
			this.loading = true;
			setTimeout(async()=>{
				let result = await toExamineTcm(this.addForm)
				if (result.code === 200) {
					this.$message({ type: 'success', message: '已提交！'});
					this.parentMethod(); // 更新数据驱动 => 父组件 shopPlan
					this.exaDialogVisible = false;
					this.loading = false;
				} else {
					this.$message.error(result.message)
					this.exaDialogVisible = false;
					this.loading = false;
				}
			},888)
		},
		//确定审核
		async exaSubmit(){
			this.addForm.state = 4
			this.addForm.reviewId = JSON.parse(localStorage.getItem('userInfo')).userId;
			let result = await toExamineTcm(this.addForm)
			if (result.code === 200) {
				this.$message({ type: 'success', message: '已审核！'});
				this.parentMethod(); // 更新数据驱动 => 父组件 shopPlan
				this.exaDialogVisible = false;
			} else {
				this.$message.error('审核失败！'+res.message)
			}
		},
		// 拒绝审核
		refuseExamine(){
			this.$confirm('此操作将回退该条数据状态, 是否继续?', '提示', {
			  confirmButtonText: '确定',
			  cancelButtonText: '考虑一下',
			  type: 'warning'
			}).then(async() => {
				this.addForm.state = 0
				let result = await toExamineTcm(this.addForm)
				if (result.code === 200) {
					this.parentMethod(); // 更新数据驱动 => 父组件 shopPlan
					this.exaDialogVisible = false;
				} else {
					this.$message.error('不准不审核！'+res.message)
				}
			}).catch(() => {
				this.$message({ type: 'info', message: '考虑一下'});          
			});
		},
		//确定过单
		async passOrderSubmit(){
			this.addForm.state = 5
			this.addForm.passingOrdersId = JSON.parse(localStorage.getItem('userInfo')).userId;
			console.log(this.addForm,'过单数据');
			let result = await toExamineTcm(this.addForm)
			if (result.code === 200) {
				this.$message({ type: 'success', message: '已过单！'});
				this.parentMethod(); // 更新数据驱动 => 父组件 shopPlan
				this.exaDialogVisible = false;
			} else {
				this.$message.error('过单失败！'+res.message)
			}
		},
		// 拒绝过单
		refusePassOrder(){
			this.$confirm('此操作将回退该条数据状态, 是否继续?', '提示', {
			  confirmButtonText: '确定',
			  cancelButtonText: '考虑一下',
			  type: 'warning'
			}).then(async() => {
				this.addForm.state = 2
				console.log(this.addForm);
				let result = await toExamineTcm(this.addForm)
				if (result.code === 200) {
					this.parentMethod(); // 更新数据驱动 => 父组件 shopPlan
					this.exaDialogVisible = false;
				} else {
					this.$message.error('不准不过单！'+res.message)
				}
			}).catch(() => {
				this.$message({ type: 'info', message: '考虑一下'});          
			});
		},
		// 草稿保存
		async draftSubmit(){
			 this.addForm.list.push(this.lists)
			 this.addForm.totalAmt = this.cbValue
			 this.addForm.state = 0
			 console.log(this.addForm);
			 let result = await addPurchasingPlan(this.addForm)
			 if (result.code === 200) {
			 	this.$message({
			 		type: 'success',
			 		message: '采购计划草稿：已保存！',
			 	});
			 	location.reload();
			 	this.exaDialogVisible = false;
			 } else {
			 	this.$message.error('失败！')
			 }
		},
		dy(){
			// 处理索引1的逻辑
			this.$message.warning('打印功能开发中...')
		},
		//sons
		// db events
		handledbRow(row, column, event){
			if(row){ this.form = row; this.watchDialogVisible = true } else { console.log('fail'); }
			// console.log(this.form);
			this.formdisabled = true
			// this.form.textSpell = this.makePy(this.form.label).toLocaleUpperCase()
			// console.log(this.form.textSpell);
		},
		// col 里面包含了表头字段和名称，list 是表格数据
		columnWidth(col, list) {
		  let prop = col.prop,lab = col.lab;
		  let width = 40; // 设定一个最小值
		  let maxlenStr = ""; // 最长字符串
		  for (let info of list) {
			if (maxlenStr < (info[prop] + "").length) maxlenStr = info[prop];
		  }
		  width = Math.max(width, len(lab), len(maxlenStr));
		  // 表格自带的内边距(20px) 自调
		  return width + 24; // 这里加了 12px
		  function len(str) {
			// 实际分配长度可根据需要自行调整
			let length = 12;
			for (const char of str + "") {
			  // 英文小写字符 8px
			  if ("a" <= char && char <= "z") length += 8;
			  // 英文大写字符 8px
			  else if ("A" <= char && char <= "Z") length += 8;
			  // 中文字符 28px
			  else if (char >= "\u4e00" && char <= "\u9fa5") length += 28;
			  // 其他 8px
			  else length += 12;
			}
			return length;
		  }
		},
	},
	
}
</script>

<style lang="less" scoped>
.layout-app{
    width: 100%;
    height: 100%;
    display: flex;
	background-color: f8f8f8;
	/deep/ .el-dialog__header{
		padding: 4px;
		background-color: #007bb0;
	}
	/deep/ .el-select > .el-input{
		width: 100%;
	}
	/deep/ .el-form-item--mini.el-form-item, .el-form-item--small.el-form-item{
		margin-bottom: 8px;
	}
	/deep/ .el-dialog__title{
		font-size: 12px;
		color: #fff;
	}
	/deep/ .el-dialog__headerbtn {
		top: 10px;
	}
	/deep/ .el-dialog__headerbtn .el-dialog__close{
		color: #fff;
	}
	/deep/ .el-dialog__headerbtn .el-dialog__close:hover{
		background-color: brown;
	}
	/deep/ .el-dialog__body{
		padding: 8px;
	}
	/deep/ .el-divider--horizontal{
		margin: 0;
	}
	/deep/ .el-form-item__label{
		display: flex;
		justify-content: right;
		font-size: 12px;
	}
    .addAcc{
		// self
		// 选项卡
		.tabs{
		/deep/ .el-date-editor.el-input, .el-date-editor.el-input__inner{
			width: 100%;
		}
		
			.tabsMain{
				display: flex;
				flex-direction: column;
				justify-content: space-between;
				align-items: center;
				width: 100%;
				margin-bottom: 8px;
				.a{
					flex: 1;
					display: flex;
					align-items: center;
				}
				.table{
					width: 100%;
					margin-top: 12px;
					/deep/ .el-table .cell{
						font-size: 12px;
						font-weight: 400;
						color: #0c0c0c;
						text-align: left;
					}
					/* 自定义高亮颜色 */
					::v-deep .el-table__body tr.current-row > td {
					  background-color: #00557f !important;
					  color: #f9f9f9; /* 可选：修改文字颜色 */
					}
					/deep/ .el-table .el-table__cell{
						padding: 8px 0;
					}
				}
				.total{
					display: flex;
					height: 48px;
					align-items: center;
					span{
						font-size: 12px;
					}
				}
			}	
		}
		.dialog-footer{
			display: flex;
			justify-content: right;
		}
	}
}
</style>